package com.lc.projects.structure.sort;

/**
 * 归并排序
 * 将两个有序数组合并到一起
 * 
 * 1 将数组从中间划分，左边排序，右边排序。
 * 2 将两个有序数组合并到临时数组。将临时数组替换到原数组的位置。
 * @author LC
 *
 */
public class MergeSort {

	public static void sort(int[] nums, int low, int high) {
		int mid = (low + high) / 2;
		if (low < high) {
			sort(nums, low, mid);
			sort(nums, mid + 1, high);
			merge(nums, low, mid, high);
		}
	}

	public static void merge(int[] nums, int low, int mid, int high) {
		int[] temp = new int[high - low + 1];
		int i = low;
		int j = mid + 1;
		int k = 0;
		while (i <= mid && j <= high) {
			if (nums[i] < nums[j]) {
				temp[k++] = nums[i++];
			} else {
				temp[k++] = nums[j++];
			}
		}
		while (i <= mid) {
			temp[k++] = nums[i++];
		}

		while (j <= high) {
			temp[k++] = nums[j++];
		}

		for (int k2 = 0; k2 < temp.length; k2++) {
			nums[k2 + low] = temp[k2];
		}
	}

}
